//void, Obj This

Building this;
ObjList olAllyUnits, olEnemyUnits, olRescue;
Unit u;
point pt;
int i, p;

Sleep(1340+rand(GetConst("RandTimeStart"))+GetConst("AddTimeStart"));

this = This.AsBuilding();

if (!.IsValid()) {
	Sleep(10000);//will restart after 10 seconds
	return;
}
while(.IsValid){

	if(.class != "GreatTavern"){
		if( .settlement.Units.count ) 
		{
			olAllyUnits.Clear;
			olEnemyUnits.Clear;
			olRescue.Clear;
			for(i=0; i<.settlement.Units.count; i+=1) {
				u = .settlement.Units[i].AsUnit;
				if(u.player == 16 || u.player == 14){
					if(!u.IsHeirOf("CaptainOutpost") &&
					   !u.IsHeirOf("SentryOutpost") &&
					   !u.IsHeirOf("Sentry"))
						olRescue.Add(u);
				} else {
					if(.IsEnemy(u)) {
						olEnemyUnits.Add(u);
					} else {
						olAllyUnits.Add(u); 
					}
				}
				if (i % 50 == 49) Sleep(2);
			}
			olAllyUnits.ClearDead;
			olEnemyUnits.ClearDead;
			olRescue.ClearDead;
			
			if(olRescue.count > 0){
				if(olAllyUnits.count > 0){
					p = olAllyUnits[rand(olAllyUnits.count)].player;
					olRescue.SetPlayer(p);
					SwapSelectedObj(this, this);
				}
			}
			if(olEnemyUnits.count > 0){
				pt.Set(1,0);
				pt.SetLen(.radius);
				pt.Rot(rand(360));
				pt = pt + .pos;
				olEnemyUnits.SetCommand("advance", pt);
			}
		}
		
    } else {
        Sleep(20*10000);
    }

	if(.sight < 2000){
		if(EnvReadString(.player, "IncreaseSight") == "yes"){
			.SetSight(2000);
		}
	} else {
		if(!EnvReadString(.player, "IncreaseSight") == "yes"){
			if(.sight != 1600)
				.SetSight(1600);
		}
	}    
	Sleep(4000);
}
